/**************************************************************/
/*  This file is licensed from, and is a trade secret of:     */
/*                                                            */
/*    Mercury Computer Systems, Incorporated                  */
/*    199 Riverneck Road                                      */
/*    Chelmsford, Massachusetts 01824-2820                    */
/*    United States of America                                */
/*    Telephone + 1 978 256-1300                              */
/*                                                            */
/*  Refer to your Software License Agreement for provisions   */
/*  on use, duplication, or disclosure.                       */
/*  US. Government users and prime contractors are also       */
/*  governed by the following Data Rights Notice:             */
/*  Use, duplication or disclosure by the US. Government is   */
/*  subject to the provisions set forth in FAR 52.227-14 for  */
/*  restricted rights or other agency data rights provisions  */
/*  on commercial software and documentation, as applicable.  */
/*                                                            */
/*  This file: (a) was developed at private expense, and no   */
/*  part was developed with government funds, (b) is a        */
/*  trade secret of Mercury Computer Systems, Inc. for the    */
/*  purposes of the Freedom of Information Act, (c) is        */
/*  "commercial computer software" subject to limited         */
/*  utilization as provided in the above noted Software       */
/*  License Agreement and (d) is in all respects data         */
/*  belonging exclusively to Mercury Computer Systems, Inc..  */
/*                                                            */
/**************************************************************/

/******************************************************************/
/* Copyright (c) 1999-2003, Mercury Computer Systems, Inc.,       */
/* Chelmsford MA.,and all third party embedded software sources.  */
/* All rights reserved under the Copyright laws of US. and        */
/* international treaties.                                        */
/*                                                                */
/* Patent Pending                                                 */
/******************************************************************/


//$COPYRIGHT_END

#include <cstdlib>
#include <cstdio>
#include <string>
#include "RsHop.h"

using namespace std;

extern "C" {
  RSHOP_EXPORT
  POA_CF::Resource *
  CreateRsHopEncoder (const char * identifier)
  {
    RsHopEncoder * encoder;

    if (RsHopEncoder::Create (encoder, identifier) != success) {
      return 0;
    }

    return (POA_CF::Resource *) encoder;
  }
}

status
RsHopEncoder::Create (RsHopEncoder *& handle,
                      const char * identifier)
{
  RsHopEncoder * Temp = new RsHopEncoder (identifier);

  if (!Temp) {
    return fail;
  }

  if (!Temp->Init ()) {
    handle = 0;
    return fail;
  }

  handle = Temp;
  return success;
}

RsHopEncoder::RsHopEncoder (const char * identifier)
  : CF__Resource_impl(identifier),
    m_threadrunning(false),
    m_bStop(false)
{
  unsigned int input_buffer_size;
  unsigned int output_buffer_size;

  // initialize buffer(s)
  input_buffer_size = 147+7;
  m_input = new char[input_buffer_size];
  output_buffer_size = 176;
  m_output = new char[output_buffer_size];

  // define port(s)
  m_rshopin = new BitPacketizerInPort_impl (input_buffer_size);
  m_rshopout = new RsHopOutPort_impl (m_output, output_buffer_size);
}

RsHopEncoder::~RsHopEncoder ()
{
  delete m_input;
  delete m_output;
  delete m_rshopin;
  delete m_rshopout;
  delete m_gf;
  delete m_genpoly;
  delete m_encMsg;
}

status
RsHopEncoder::Init ()
{
#ifdef MCS_VERBOSE
  std::cout << "RsHopEncoder: Initializing." << std::endl;
#endif

  unsigned int hop_prim_poly[6] = {1, 0, 1, 0, 0, 1};
  unsigned int hop_gen_poly[3] = {8, 6, 1};

  // Initialize the parameters.
  m_n = 16;
  m_k = 14;
  m_N = 31;
  m_K = 29;
  m_m = 5;
  m_b = 1;

  m_gf = new galois::GaloisField (m_m, hop_prim_poly);

  galois::GaloisFieldElement gfe_hop_genpoly[3] = 
    {
      galois::GaloisFieldElement(m_gf, hop_gen_poly[0]),
      galois::GaloisFieldElement(m_gf, hop_gen_poly[1]),
      galois::GaloisFieldElement(m_gf, hop_gen_poly[2]),
    };

  m_genpoly = new galois::GaloisFieldPolynomial (m_gf, 2, gfe_hop_genpoly);

  if ((m_n-m_k) % 2 == 0) {
    m_t = (m_n - m_k) / 2;
  }
  else {
    m_t = (m_n - m_k - 1) / 2;
  }


  m_encMsg = new galois::GaloisFieldPolynomial (m_gf, m_N-1);
  return success;
}

void
RsHopEncoder::RunWorker (void * param)
{
  RsHopEncoder * component = (RsHopEncoder *) param;

#ifdef MCS_VERBOSE
  std::cout << "RsHopEncoder: Component is running." << std::endl;
#endif

  component->RunLoop ();

#ifdef MCS_VERBOSE
  std::cout << "RsHopEncoder: Component is stopping." << std::endl;
#endif
}

status
RsHopEncoder::RunLoop ()
{
  while (!m_bStop) {
    Run ();
  }

  return success;
}

void
RsHopEncoder::start ()
  throw (CORBA::SystemException, CF::Resource::StartError)
{
  if (m_threadrunning) {
    return;
  }

  m_threadrunning = true;
  m_thread.start (RunWorker, (void *) this);
  CF__Resource_impl::start();
}

void
RsHopEncoder::stop ()
  throw (CORBA::SystemException, CF::Resource::StopError)
{
  m_bStop = true;
}

CORBA::Object_ptr
RsHopEncoder::getPort (const CORBA::Char * name)
  throw (CORBA::SystemException, CF::PortSupplier::UnknownPort)
{
  string temp (name);

  if (temp == "RsHopEncoderIn") {
    return m_rshopin->getPort ();
  }
  else if (temp == "RsHopEncoderOut") {
    return m_rshopout->getPort ();
  }
  else {
    throw CF::PortSupplier::UnknownPort ();
  }
}

status
RsHopEncoder::Run ()
{
  unsigned int i, num_read=0;
  unsigned int m_input_count = m_rshopin->GetData (&m_input);

  if (m_input_count == 0) {
    return fail;
  }
  else if (m_input_count < m_k) {
    // Not enough data in buffer; wait for more.
    m_rshopin->ReleaseDataBuffer (0);
    return success;
  }

  unsigned int m_output_count = 0;

#ifdef MCS_VERBOSE
  std::cout << "RsHopEncoder: Received " << m_input_count << " samples." << std::endl;
#endif

  while (m_input_count >= m_k) {
    // Shift the polynomial n-k units (for the parities).
    for (i = 0; i < m_n - m_k; i++) {
      (*m_encMsg)[i] = 0;
    }

    // Fill in the sequence to be encoded.
    for (i = m_n-m_k; i < m_n; i++) {
      (*m_encMsg)[i] = m_input[i-(m_n-m_k)];
    }

    // Zero-pad the beginning.
    for (i = m_n; i < m_N-1; i++) {
      (*m_encMsg)[i] = 0;
    }

    galois::GaloisFieldPolynomial hopParities = *m_encMsg % *m_genpoly;
    galois::GaloisFieldPolynomial hopEncoderOut = *m_encMsg + hopParities; 

    for (i=0; i < m_n; i++) {
      m_output[m_output_count+i] = (char) hopEncoderOut[i].poly();
    }

    m_input_count -= m_k;
    num_read += m_k;
    m_input += m_k;
    m_output_count += m_n;
  } // while

#ifdef MCS_VERBOSE
  std::cout << "RsHopEncoder: Pushing " << m_output_count << " samples." << std::endl;
#endif

  m_rshopout->pushData (m_output, m_output_count);
  m_rshopin->ReleaseDataBuffer (num_read);
  return success;
}
